/* machine_timer.c */

#include <stdio.h>

#include "py/runtime.h"

#include "machine_timer.h"
#include "hal_tim_basic.h"

#include "board_init.h"

/*
 * Declerations.
 */

/* Local functions. */
static void machine_timer_enable_clock(uint32_t id, bool enable);

STATIC mp_obj_t machine_timer_obj_init_helper(const machine_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args);

/* Class method, which would be called by class name. */
STATIC     void machine_timer_obj_print(const mp_print_t *print, mp_obj_t o, mp_print_kind_t kind);
       mp_obj_t machine_timer_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args);


/* Instance methods, which would be called by class instance name. */
STATIC mp_obj_t machine_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args);

/*
 * Functions.
 */


/* timer.__del__(). */
STATIC mp_obj_t machine_timer___del__(mp_obj_t self_in)
{
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);

    /* disable the timer. */
    TIM_BASIC_Stop(self->timer_port);
    machine_timer_enable_clock(self->timer_id, false);

    //PIT_StopTimer(PIT, self->channel);
    //MP_STATE_PORT(timer_table)[self->id] = NULL;
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer___del___obj, machine_timer___del__);

/* timer.deinit(). */
STATIC mp_obj_t machine_timer_deinit(mp_obj_t self_in)
{
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);

    /* disable the timer. */
    TIM_BASIC_Stop(self->timer_port);
    machine_timer_enable_clock(self->timer_id, false);

    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_deinit_obj, machine_timer_deinit);


/* timer.init(). */
STATIC mp_obj_t machine_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
    /* args[0] is machine_pin_obj_t. */
    //printf("machine_timer_init().\r\n");
    return machine_timer_obj_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
MP_DEFINE_CONST_FUN_OBJ_KW(machine_timer_init_obj, 1, machine_timer_init);

/* init parameter list. */
enum
{
    TIMER_INIT_ARG_mode = 0,
    TIMER_INIT_ARG_callback,
    TIMER_INIT_ARG_period,
};

STATIC mp_obj_t machine_timer_obj_init_helper (
    const machine_timer_obj_t *self, /* machine_timer_obj_t类型的变量，包含硬件信息 */
    size_t n_args,                   /* 位置参数数量 */
    const mp_obj_t *pos_args,        /* 位置参数清单 */
    mp_map_t *kw_args )              /* 关键字参数清单结构体 */
{
    static const mp_arg_t allowed_args[] =
    {
        [TIMER_INIT_ARG_mode    ]{ MP_QSTR_mode,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIMER_MODE_PERIODIC} },
        //[TIMER_INIT_ARG_callback]{ MP_QSTR_callback, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
        [TIMER_INIT_ARG_callback]{ MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
        [TIMER_INIT_ARG_period  ]{ MP_QSTR_period,   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
        //[TIMER_INIT_ARG_tick_hz ]{ MP_QSTR_tick_hz,      MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
        //[TIMER_INIT_ARG_freq    ]{ MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
    };

    /* 解析参数 */
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];

    //printf("machine_timer_obj_init_helper()\r\n");

    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    self->conf->callback = args[TIMER_INIT_ARG_callback].u_obj;
    self->conf->mode     = args[TIMER_INIT_ARG_mode].u_int;
    self->conf->period   = args[TIMER_INIT_ARG_period].u_int;
    //self->conf->tick_hz  = args[TIMER_INIT_ARG_tick_hz].u_int;
    //self->conf->freq     = BOARD_TIM_BASIC_FREQ;

    machine_timer_enable_clock(self->timer_id, true);

    /* Set the counter counting step. */
    TIM_BASIC_Init_Type tim_init;
    tim_init.ClockFreqHz = BOARD_TIM_BASIC_FREQ;
    tim_init.StepFreqHz = 1000; /* 1ms. */
    tim_init.Period = self->conf->period;
    tim_init.EnablePreloadPeriod = true;
    tim_init.PeriodMode = (self->conf->mode == TIMER_MODE_PERIODIC) ? TIM_BASIC_PeriodMode_Continuous : TIM_BASIC_PeriodMode_OneTimeRun;
    TIM_BASIC_Init(self->timer_port, &tim_init);

    /* Enable interrupt. */
    NVIC_EnableIRQ(self->timer_irqn);
    TIM_BASIC_EnableInterrupts(self->timer_port, TIM_BASIC_INT_UPDATE_PERIOD, true);

    /* Start the counter. */
    TIM_BASIC_Start(self->timer_port);

    //printf("machine_timer_obj_init_helper(), done.\r\n");

    return mp_const_none;
}

static void machine_timer_irq_handler(uint32_t timer_id)
{
    const machine_timer_obj_t * self = machine_timer_objs[timer_id];

    uint32_t flags = TIM_BASIC_GetInterruptStatus(self->timer_port);
    if (0u != (flags & TIM_BASIC_STATUS_UPDATE_PERIOD) )
    {
        if (self->conf->callback)
        {
            mp_sched_schedule(self->conf->callback, MP_OBJ_FROM_PTR(self));
            //printf("*");
        }
    }
    TIM_BASIC_ClearInterruptStatus(self->timer_port, flags);

    if (self->conf->mode == TIMER_MODE_ONE_SHOT)
    {
        TIM_BASIC_Stop(self->timer_port);
    }
}

STATIC     void machine_timer_obj_print(const mp_print_t *print, mp_obj_t o, mp_print_kind_t kind)
{
    /* o is the machine_pin_obj_t. */
    (void)kind;
    const machine_timer_obj_t *self = MP_OBJ_TO_PTR(o);
    qstr mode = self->conf->mode == TIMER_MODE_ONE_SHOT ? MP_QSTR_ONE_SHOT : MP_QSTR_PERIODIC;
    mp_printf(print, "Timer(channel=%d, mode=%q, period=%dms)",
        self->timer_id, mode, self->conf->period);
}

/* return an instance of machine_timer_obj_t. */
mp_obj_t machine_timer_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

    const machine_timer_obj_t *timer = timer_find(args[0]);

    //machine_timer_enable_clock(timer->timer_id, true);
    //printf("machine_timer_obj_make_new()\r\n");

    if ( (n_args >= 1) || (n_kw >= 0) )
    {
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); /* 将关键字参数从总的参数列表中提取出来，单独封装成kw_args。 */
        machine_timer_obj_init_helper(timer, n_args - 1, args + 1, &kw_args);
    }

    return (mp_obj_t)timer;
}


/* class locals_dict_table. */
STATIC const mp_rom_map_elem_t machine_timer_locals_dict_table[] =
{
    /* Class instance methods. */
    { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&machine_timer___del___obj) },
    { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_timer_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_timer_deinit_obj) },

    /* Class attributes. */
    { MP_ROM_QSTR(MP_QSTR_ONE_SHOT), MP_ROM_INT(TIMER_MODE_ONE_SHOT) },
    { MP_ROM_QSTR(MP_QSTR_PERIODIC), MP_ROM_INT(TIMER_MODE_PERIODIC) },

};
STATIC MP_DEFINE_CONST_DICT(machine_timer_locals_dict, machine_timer_locals_dict_table);


const mp_obj_type_t machine_timer_type =
{
    { &mp_type_type },
    .name        = MP_QSTR_Timer,
    .print       = machine_timer_obj_print, /* __repr__(), which would be called by print(<ClassName>). */
    .make_new    = machine_timer_obj_make_new, /* create new class instance. */
    .locals_dict = (mp_obj_dict_t *)&machine_timer_locals_dict,
};

/*
 * User functions.
 */
/* 格式化timer对象，传入参数无论是已经初始化好的pin对象，还是一个表示timer清单中的索引编号，通过本函数都返回一个期望的timer对象。 */
const machine_timer_obj_t *timer_find(mp_obj_t user_obj)
{
    /* 如果传入参数本身就是一个Timer的实例，则直接送出这个Timer。 */
    if ( mp_obj_is_type(user_obj, &machine_timer_type) )
    {
        return user_obj;
    }

    /* 如果传入参数是一个Timer ID号，则通过索引在Timer清单中找到这个通道，然后送出这个通道的实例化对象。 */
    if ( mp_obj_is_small_int(user_obj) )
    {
        uint8_t timer_idx = MP_OBJ_SMALL_INT_VALUE(user_obj);
        if ( timer_idx < MACHINE_TIMER_NUM )
        {
            return machine_timer_objs[timer_idx];
        }
    }

    mp_raise_ValueError(MP_ERROR_TEXT("Timer doesn't exist."));
}

void TIM6_IRQHandler(void) { machine_timer_irq_handler(0); }
void TIM7_IRQHandler(void) { machine_timer_irq_handler(1); }

static void machine_timer_enable_clock(uint32_t id, bool enable)
{
    switch (id)
    {
        case 0u:
            RCC_EnableAPB1Periphs(RCC_APB1_PERIPH_TIM6, enable);
            break;
        case 1u:
            RCC_EnableAPB1Periphs(RCC_APB1_PERIPH_TIM7, enable);
            break;
        default:
            break;
    }
}

/* EOF. */

